package com.qf.student.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.student.common.Const;
import com.qf.student.response.R;
import com.qf.student.response.RCodes;
import com.qf.student.utils.TokenUtils;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author YaoJiXing
 * created 2022/11/22 22:01
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");

        // 如果请求方式是 OPTIONS 就代表预处理（预检请求）由浏览器发送
        if (request.getMethod().equals("OPTIONS")) {
            //直接放行
            return true;
        }

        // String jwt = request.getParameter("jwt");
        // 获取保存在头信息中的 token
        String jwt = request.getHeader(Const.AUTHORIZATION);
        R r = null;

        try {
            Claims c = TokenUtils.getTokenValue(jwt);
        } catch (ExpiredJwtException e) { //令牌过期
            r = R.createFAIL(RCodes.NOT_LOGIN.getCode(), "登录已过期，请重新登录");
        } catch (MalformedJwtException e) { //错误令牌
            r = R.createFAIL(RCodes.NOT_LOGIN.getCode(), "登录信息有误，请重新登录");
        } catch (SignatureException e) { //签名错误
            r = R.createFAIL(RCodes.NOT_LOGIN.getCode(), "登录信息有误，请重新登录");
        } catch (IllegalArgumentException e) { //非法参数
            r = R.createFAIL(RCodes.NOT_LOGIN.getCode(), "登录信息有误，请重新登录");
        }

        if (r != null) {
            ObjectMapper obj = new ObjectMapper();
            //把 R 转为 JSON
            String jsonString = obj.writeValueAsString(r);
            response.getWriter().println(jsonString);
            //r不为空，证明出现了异常
            return false;
        }
        return true;
    }
}
